import {getTypesApi,addNewTypeApi,deleteTypeApi} from "@/services/type"
export default {
    namespace:"type",
    state:{
        typeList:[],
        typeTest:'type测试数据',

    },
    effects:{
        *_initList(_,{put,call}){
            const resp = yield call(getTypesApi)
            console.log(resp,"类型")
            yield put({
                type:'initList',
                payload:resp.data
            })
        },
        *_addType(action,{put,call}){
            const payload = action.payload
            const resp = yield call(addNewTypeApi,payload)
           // 本地
           const target = resp.data
           yield put({
               type:'addType',
               payload:target
           })
        },
        *_deleteType(action,{put,call}){
            const id = action.payload.id
            const resp=yield call(deleteTypeApi,id)
            yield put({
                type:'deleteType',
                payload:id
            })
        }
    },
    reducers:{
        initList(state,action){
            const newState = {...state};
            newState.typeList = action.payload
            return newState
        },
        addType(state,action){
            const payload = action.payload
            const newState = {...state};
            const tempArr = [...newState.typeList];
            tempArr.push(payload);
            newState.typeList = tempArr;
            return newState


        },
        deleteType(state,action){
            const payload = action.payload
            const newState = {...state};
            const tempArr = [...newState.typeList];
            // 找到下标
            const index = tempArr.findIndex(item=>{
                return item._id===payload
            })
            tempArr.splice(index,1);
            newState.typeList = tempArr;
            return newState
        }
    }

}